package gorm

import "github.com/jinzhu/gorm"

func Create() {
	db := GetDB()

	u1 := UserInfo{ID: 0, Name: "七米", Gender: "男", Hobby: "篮球"}
	u2 := UserInfo{ID: 0, Name: "沙河娜扎", Gender: "女", Hobby: "足球"}

	//生成的insert语句排除0值，数据库中为表默认值
	db.Create(&u1)
	db.Create(&u2)
}

func Update(id int64) {
	db := GetDB()

	//单字段更新
	db.Model(UserInfo{ID: id}).UpdateColumn("name", "hello")
	//多字段更新
	db.Model(UserInfo{ID: id}).UpdateColumns(UserInfo{Name: "aa", Gender: "女"})

	//单字段更新
	db.Model(UserInfo{}).Where("id=?", id).Update("name", "林芳伊")
	//多字段更新
	db.Model(UserInfo{ID: id}).Updates(map[string]interface{}{
		"name":  "aa",
		"hobby": "hobby",
	})
	//多字段更新  struct类型，只update非0值
	db.Model(UserInfo{ID: id}).Updates(UserInfo{Name: "aa", Gender: "gg"})
}

func Update2() {
	db := GetDB()
	var user = User{ID: 111}
	// 更新单个属性，如果它有变化
	db.Model(&user).Update("name", "hello")
	//// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;

	// 根据给定的条件更新单个属性
	db.Model(&user).Where("active = ?", true).Update("name", "hello")
	//// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true;

	// 使用 map 更新多个属性，只会更新其中有变化的属性
	db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})
	//// UPDATE users SET name='hello', age=18, active=false, updated_at='2013-11-17 21:34:10' WHERE id=111;

	// 使用 struct 更新多个属性，只会更新其中有变化且为非零值的字段
	db.Model(&user).Updates(User{Name: "hello", Age: 18})
	//// UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;

	// 警告：当使用 struct 更新时，GORM只会更新那些非零值的字段
	// 对于下面的操作，不会发生任何更新，"", 0, false 都是其类型的零值
	db.Model(&user).Updates(User{Name: "", Age: 0})

	//批量更新
	db.Table("users").Where("id IN (?)", []int{10, 11}).Updates(map[string]interface{}{"name": "hello", "age": 18})
	//// UPDATE users SET name='hello', age=18 WHERE id IN (10, 11);

	db.Model(&user).Update("age", gorm.Expr("age * ? + ?", 2, 100))
	//// UPDATE `users` SET `age` = age * 2 + 100, `updated_at` = '2020-02-16 13:10:20'  WHERE `users`.`id` = 1;

	db.Model(&user).Updates(map[string]interface{}{"age": gorm.Expr("age * ? + ?", 2, 100)})
	//// UPDATE "users" SET "age" = age * '2' + '100', "updated_at" = '2020-02-16 13:05:51' WHERE `users`.`id` = 1;
}

func Delete(id int64) {
	db := GetDB()

	//默认主键删除
	db.Delete(UserInfo{ID: id})

	//where条件
	db.Where("id=?", id).Delete(&UserInfo{})
	db.Delete(&UserInfo{}, "id=?", id) //内联条件

	var user = User{ID: 111}
	// 删除现有记录
	db.Delete(&user)
	//// DELETE from user where id=111;
}
